<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <link th:replace="head::headerFragment('数据源管理')">
</head>
<body class="gray-bg">

<div class="col-sm-12" style="margin-top: 50px">
     <div id="treeJobScript" class="ztree"></div>
</div>
<div id="rMenu" style="display: none">
    <ul>
        <li id="m_add" onclick="addTreeNodeDir();">新建节点</li>
        <li id="m_rename" onclick="renameTreeNode();">重命名</li>
        <li id="m_del" onclick="removeTreeNode();">删除</li>
    </ul>
</div>

<SCRIPT LANGUAGE="JavaScript">
    var js_setting = {
        view: {
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true,
                pIdKey: "pid",
                rootPId: 0
            }
        },
        check: {
            enable: false
        },
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false
        },
        callback: {
            onRightClick: OnRightClick,
            beforeRemove: zTreeBeforeRemove,
            beforeDrop: zTreeBeforeDrop,
            beforeAsync: zTreeBeforeAsync,
            beforeRename: zTreeBeforeRename,
            onClick: zTreeOnClick,
            onExpand: zTreeOnExpand
        },
        async: {
            enable: true,
            autoParam: ['id'],
            url: '/dataSource/tree',
            type: 'get'
        }
    };


    function zTreeBeforeAsync(treeId, treeNode) {
        return true;
    }

    function OnRightClick(event, treeId, treeNode) {
        if (treeNode.name == "datasource") {
            zTree.cancelSelectedNode();
            showRMenu("root", event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    function showRMenu(type, x, y) {
        $("#rMenu").show();
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_add").show();
            $("#m_rename").show();
            $("#m_del").show();
        }
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    var addCount = 1;

    function addTreeNodeDir() {
        hideRMenu();
        var newNode = {name: "增加" + (addCount++)};
        var newNode_;
        if (zTree.getSelectedNodes()[0]) {
            newNode_ = zTree.addNodes(zTree.getSelectedNodes()[0], newNode);
        } else {
            newNode_ = zTree.addNodes(zTree.getNodesByParam("name", "datasource", null)[0], newNode);
        }
        zTree.editName(newNode_[0]);
    }

    //使节点处于编辑状态
    function renameTreeNode() {
        hideRMenu();
        zTree.editName(zTree.getSelectedNodes()[0]);
    }

    //删除节点
    function removeTreeNode() {
        hideRMenu();
        var nodes = zTree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            if (nodes[0].children && nodes[0].children.length > 0) {
                var msg = "要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！";
                if (confirm(msg) == true) {
                    zTreeBeforeRemove(nodes[0].id, nodes[0]);
                    zTree.removeNode(nodes[0]);
                }
            } else {
                zTreeBeforeRemove(nodes[0].id, nodes[0]);
                zTree.removeNode(nodes[0]);
            }
        }
    }

    //删除节点（与后端交互）
    function zTreeBeforeRemove(treeId, treeNode) {
        // if(treeNode.children&&treeNode.children.length) return false;
        var isParent = 1;
        if (!treeNode.getNextNode() && !treeNode.getPreNode()) {
            isParent = 0
        }
        var data = {
            id: treeNode.id,
            pid: treeNode.pid,
            isParent: isParent
        };
        $.ajax({
            type: 'POST',
            url: '/dataSource/remove',
            data: data,
            success: function (data) {
                // var zTree = $.fn.zTree.getZTreeObj(treeId);
                // zTree.removeNode(treeNode);
                toastr.success('Modify successfully!', 'Success')
            },
            error: function (err) {
                toastr.error('An error has occurred.', 'Error!')
            }
        });
        return true
    }

    var zTree, rMenu;
    $(document).ready(function () {
        $.fn.zTree.init($("#treeJobScript"), js_setting);
        zTree = $.fn.zTree.getZTreeObj("treeJobScript");
        rMenu = $("#rMenu");
    });

    // 跟新/新建节点
    function zTreeBeforeRename(treeId, treeNode, newName, isCancel) {
        if (newName.trim() == '') return false;
        if (!isCancel) {
            var data = {
                id: treeNode.id,
                name: newName,
                pid: treeNode.pid,
                isParent: treeNode.isParent ? 1 : 0,
                sort: treeNode.getPreNode() ? treeNode.getPreNode().sort + 1 : 1
            };
            $.ajax({
                type: 'POST',
                url: '/dataSource/update',
                data: data,
                dataType: 'json',
                success: function (data) {
                    treeNode.id = data.id;
                    treeNode.sort = data.sort;
                    toastr.success('Modify successfully!', 'Success')
                },
                error: function (err) {
                    toastr.error('An error has occurred.', 'Error!')
                }
            })
        }
        return true
    }

    function zTreeOnClick(event, treeId, treeNode) {
        if (treeNode.isParent == 1) {
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            zTree.expandNode(treeNode, null, null, null);
        }
    }

    function zTreeOnExpand(event, treeId, treeNode) {
        if (treeNode.isAdd) {
            delete treeNode.isAdd;
            var zTree = $.fn.zTree.getZTreeObj(treeId);
            var name = treeNode.children ? treeNode.children[treeNode.children.length - 1].name : '';
            var newNodes = zTree.addNodes(treeNode, {name: name}, true);
            zTree.editName(newNodes[0]);
        }
    }

    function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
        if (targetNode == null || moveType == "inner") return false; //禁止将节点拖拽成为根节点
        // if(treeNodes[0].type!=targetNode.type) return false; //禁止跨节点拖拽
        // if(treeNodes[0].level!=targetNode.level) return false; //禁止将节点拖拽成为子节点
        var data = {
            id: treeNodes[0].id,
            pid: treeNodes[0].pid,
            targetPid: targetNode.pid,
            sort: treeNodes[0].sort,
            targetSort: targetNode.sort,
            name: treeNodes[0].name
        }
        $.ajax({
            type: 'POST',
            url: '/dataSource/drag',
            data: data,
            success: function (data) {
                toastr.success('Modify successfully!', 'Success')
            },
            error: function (err) {
                toastr.error('An error has occurred.', 'Error!')
            }
        });
        return true
    };


</SCRIPT>

</body>

</html>

